<?php

namespace app\admin\controller\workteam;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 记账管理
 */
class Accountlog extends Backend
{

    protected $model = null;
    protected $taskfeild = [];
    protected $projectfeild = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new  \app\admin\model\workteam\Accountlog();
    }

    /**
     * 查看
     */
    public function index($project_id=null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $filter_w=[];
        $project_id?$filter_w['project_id'] = $project_id:'';

        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->with([
                    'project' => function ($q) {
                        $q->field('id,name,number');
                    }])
                ->where($filter_w)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $this->assignconfig("typeList", $this->model->getTypeList());
        return $this->view->fetch();
    }


    /**
     * 支出添加
     */
    public function add()
    {
        $typeList=$this->model->getTypeList();

        if ($this->request->isPost()){
            $params = $this->request->post("row/a");

            $params = $this->preExcludeFields($params);

            //判断类型
            if (!isset($typeList[$params['type']]))
                $this->error(__("费用类型错误"));

            $projectModel=new  \app\admin\model\workteam\Project();
            $prow = $projectModel->where('id',$params['project_id'])->find();
            if (!$prow) {
                $this->error(__('项目不存在'));
            }

            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException(true)->validate($validate);
                //判断金额是否是数字
                if (!is_numeric($params['money'])||$params['money']==0)
                    \exception(__("费用必须是数字,且不能为0。"));
                //因为是支出，所有金额都应该是负数
                if ($params['money']>0)
                    $params['money'] *= -1;
                $result = $this->model->allowField(true)->save($params);
                //项目添加支出金额
                if ($result) {
                    $prow->expenses=$prow->expenses+$params['money'];
                    $prow->save();
                }


                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }

        }
        $this->view->assign("typeList",$typeList);
        return $this->view->fetch();
    }

    /**
     * 编辑
     * @internal
     */
    public function edit($ids = null)
    {
        $this->error();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $row = $this->model->where('id', $ids)->find();
            if ($row) {

                $result = false;
                Db::startTrans();
                try {
                    //删减项目支出费用
                    $row->project->expenses=$row->project->expenses - $row->money;
                    $row->project->save();
                    $result=$row->delete();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }

            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * @internal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $this->error();
    }


}
